package com.itheima.test2.server;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ServerDemo {
    public static void main(String[] args) {
        UpThreadPoll();
    }

    //创建线程池
    public static void UpThreadPoll(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                3,
                5,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        try {
            ServerSocket socket = new ServerSocket(10086);
            while (true){
                //服务器跟客户端建立连接
                Socket accept = socket.accept();
                SocketRunnable sr = new SocketRunnable(accept);
                threadPoolExecutor.submit(sr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class SocketRunnable implements Runnable{

    private Socket socket;

    //共享一个socket
    public SocketRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedInputStream reader = new BufferedInputStream(socket.getInputStream());
            byte[] bytes = new byte[1024];
            int i;
            while ((i = reader.read(bytes)) != -1){
                synchronized ("abc"){
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Test/src/com/itheima/test2/server/tupian" + UUID.randomUUID() + ".jpg",true));
                    bos.write(bytes,0,i);
                    bos.flush();
                    BufferedWriter writer1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    writer1.write("true" + "\r\n");
                    writer1.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
